package ucuserslogic

import (
	"context"
	"fmt"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/zeromicro/go-zero/core/logx"
	"go.uber.org/zap"
	"math/rand"
	"navi-mumbai/app/rpc/usercenter/internal/svc"
	"navi-mumbai/app/rpc/usercenter/pb"
	"navi-mumbai/common/key/userkey"
	"navi-mumbai/common/utils"
	"strconv"
	"strings"
	"time"
)

var cacheMumbaiUserAccountSmsVerifyCodePhoneNoPrefix = "cache:mumbai:userAccount:smsVerifyCode:phoneNo"

type GetSmsVerifyCodeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	lRand  *rand.Rand
	logx.Logger
}

func NewGetSmsVerifyCodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetSmsVerifyCodeLogic {
	return &GetSmsVerifyCodeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
		lRand:  rand.New(rand.NewSource(time.Now().UnixNano())),
	}
}

func (l *GetSmsVerifyCodeLogic) GenValidateCode(width int) string {
	numeric := [10]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	r := len(numeric)

	var sb strings.Builder
	for i := 0; i < width; i++ {
		fmt.Fprintf(&sb, "%d", numeric[l.lRand.Intn(r)])
	}
	return sb.String()
}

// 获取短信验证码
func (l *GetSmsVerifyCodeLogic) GetSmsVerifyCode(in *pb.GetSmsVerifyCodeReq) (*pb.GetSmsVerifyCodeResp, error) {
	defer utils.RecoverPanic()

	client, err := sdk.NewClientWithAccessKey("ap-southeast-1", userkey.AliBaBaCloudAccessKey, userkey.AliBaBaCloudAccessSecret)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return &pb.GetSmsVerifyCodeResp{RetCode: 0}, err
	}
	l.Logger.Infof("GetSmsVerifyCodeReq uid %d receive area no %d phone no %d", in.AreaNo, in.PhoneNo)

	vCode := l.GenValidateCode(6)
	vMsg := "LUCKYGAMES Verification Code{" + vCode + "} valid within 5 minutes"

	k := fmt.Sprintf("%s%v:%v", cacheMumbaiUsercenterUserAccountVerifyCodeAreaNoPhoneNoPrefix, in.AreaNo, in.PhoneNo)
	err = l.svcCtx.RedisClient.Setex(k, vCode, 36000000)
	if err != nil {
		l.Logger.Errorf("GetSmsVerifyCodeReq set verify code failed! key %s value %s", k, vCode)
		l.Logger.Errorf("err == ", zap.Error(err))
		return &pb.GetSmsVerifyCodeResp{RetCode: 0}, err
	}

	request := requests.NewCommonRequest()
	request.Method = "POST"
	request.Scheme = "https" // https | http
	request.Domain = userkey.AliBaBaCloudSmsDomain
	request.Version = userkey.AliBaBaCloudSmsVersion
	request.ApiName = userkey.AliBaBaCloudApi
	request.QueryParams["To"] = strconv.Itoa(int(in.AreaNo)) + strconv.Itoa(int(in.PhoneNo))
	request.QueryParams["RegionId"] = userkey.AliBaBaRegionId
	request.QueryParams["Message"] = vMsg

	response, err := client.ProcessCommonRequest(request)
	l.Logger.Infof("GetSmsVerifyCodeReq return result %s ", response.GetHttpContentString())
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return &pb.GetSmsVerifyCodeResp{RetCode: 0}, err
	}

	return &pb.GetSmsVerifyCodeResp{RetCode: 1}, nil
}
